package gcb.metalsys.auth;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import gcb.metalsys.entity.auth.AuthUser;
import gcb.metalsys.mapper.auth.AuthUserMapper;
import gcb.metalsys.service.auth.AuthRoleService;
import gcb.metalsys.service.auth.AuthTableService;
import gcb.metalsys.service.auth.AuthUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 登录时的认证
 * 通过用户名获取用户信息, 进行帐号信息验证
 * 验证是Spring security 内部实现的
 *  *需要在config里 注入PasswordEncoder的bean*
 * @author ReMidDream
 * @date 2018-08-17 14:55
 **/
@Component
@Slf4j
public class UserDetailService implements UserDetailsService {

    @Autowired
    private AuthUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("登录用户名 : {}",username);

        AuthUser user;
        // 根据用户名查找用户信息
        try {
             user = userMapper.selectUserAndRole(username);
        } catch (Exception e) {
            throw new InternalAuthenticationServiceException("系统异常");
        }

        if (user == null) {
            throw new InternalAuthenticationServiceException("用户名错误");
        }


        String userPassword = user.getUserPassword();


        return new User(username,userPassword,
                AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoleName()));
    }
}
